{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 给定一个净值序列，计算年化收益、最大回撤、夏普比率"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##  数据准备：净值序列"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "~~~ \n",
    "以HS300的收盘价，作为策略的净值\n",
    "\n",
    "~~~\n",
    "\n",
    "获取数据准备工作\n",
    "\n",
    "1. 安装JQDdata库，[JQData使用说明](https://www.joinquant.com/help/api/help?name=JQData#%E5%A6%82%E4%BD%95%E5%AE%89%E8%A3%85%E4%BD%BF%E7%94%A8JQData)。\n",
    "    \n",
    "2. 在聚宽申请账号，并且[申请开通JQData权限](https://www.joinquant.com/default/index/sdk?utm_campaign=JQData%E7%94%B3%E8%AF%B7&utm_medium=%E7%BD%91%E9%A1%B5&utm_source=%E8%81%9A%E5%AE%BD&gio_link_id=xRxqAjP5)。\n",
    "\n",
    "3. Python版本: Python3.7"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "pycharm": {
     "is_executing": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "auth success \n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "2015-01-05    1.000000\n",
       "2015-01-06    0.999868\n",
       "2015-01-07    1.000618\n",
       "2015-01-08    0.977405\n",
       "2015-01-09    0.973962\n",
       "                ...   \n",
       "2018-12-24    0.834317\n",
       "2018-12-25    0.828573\n",
       "2018-12-26    0.824385\n",
       "2018-12-27    0.821221\n",
       "2018-12-28    0.826752\n",
       "Name: close, Length: 975, dtype: float64"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 从聚宽JQData获取HS300从2015至2018年底，每个交易日的收盘价\n",
    "# 导入JQData库\n",
    "from jqdatasdk import *\n",
    "import pandas as pd\n",
    "\n",
    "# ID是申请时所填写的手机号；Password为聚宽官网登录密码\n",
    "auth('user','password') \n",
    "pd.set_option('display.max_rows', 10)\n",
    "\n",
    "# 获取HS300每日收盘价，时间：2015-01-01至2018-12-31\n",
    "df = get_price('000300.XSHG', start_date='2015-01-01', end_date='2018-12-31', frequency='daily', fields=['close'], skip_paused=False, fq='pre')\n",
    "\n",
    "# 净值统计：以第一个交易日收盘价为参考，计算每日净值\n",
    "first_close = df['close'][0]\n",
    "net_values = df['close']/ first_close\n",
    "net_values\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2015-01-05    1.000000\n",
       "2015-01-06    0.999868\n",
       "2015-01-07    1.000618\n",
       "2015-01-08    0.977405\n",
       "2015-01-09    0.973962\n",
       "                ...   \n",
       "2018-12-24    0.834317\n",
       "2018-12-25    0.828573\n",
       "2018-12-26    0.824385\n",
       "2018-12-27    0.821221\n",
       "2018-12-28    0.826752\n",
       "Name: close, Length: 975, dtype: float64"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "\n",
    "pd.set_option('display.max_rows', 10)\n",
    "\n",
    "# 获取HS300每日收盘价，时间：2015-01-01至2018-12-31\n",
    "df = get_price('000300.XSHG', start_date='2015-01-01', end_date='2018-12-31', frequency='daily', fields=['close'], skip_paused=False, fq='pre')\n",
    "\n",
    "# 净值统计：以第一个交易日收盘价为参考，计算每日净值\n",
    "first_close = df['close'][0]\n",
    "net_values = df['close']/ first_close\n",
    "net_values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>close</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2015-01-05</th>\n",
       "      <td>3641.54</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2015-01-06</th>\n",
       "      <td>3641.06</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2015-01-07</th>\n",
       "      <td>3643.79</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2015-01-08</th>\n",
       "      <td>3559.26</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2015-01-09</th>\n",
       "      <td>3546.72</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "              close\n",
       "2015-01-05  3641.54\n",
       "2015-01-06  3641.06\n",
       "2015-01-07  3643.79\n",
       "2015-01-08  3559.26\n",
       "2015-01-09  3546.72"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 根据日净值分别计算年化收益、最大回撤、夏普比率"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  计算年化收益\n",
    "\n",
    "- 计算公式\n",
    "    \n",
    "    $ Total Annualized Returns=Rp= ((1+P)^{\\frac{245}{n}}-1) * 100\\%  $ (245是每年的交易日天数)\n",
    "    \n",
    "    $ P=策略收益 $\n",
    "\n",
    "    $ n=策略执行天数 $\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "pycharm": {
     "is_executing": false
    }
   },
   "outputs": [],
   "source": [
    "def compute_annual_profit(days, net_value):\n",
    "    \"\"\"\n",
    "    计算年化收益\n",
    "    \"\"\"\n",
    "\n",
    "    annual_profit = 0\n",
    "    # 交易日数大于0，才计算年化收益\n",
    "    if days > 0:\n",
    "        # 计算年数\n",
    "        years = days / 245\n",
    "        # 计算年化收益\n",
    "        annual_profit = pow(net_value, 1 / years) - 1\n",
    "\n",
    "    # 将年化收益转化为百分数，保留两位小数\n",
    "    annual_profit = round(annual_profit * 100, 2)\n",
    "\n",
    "    return annual_profit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "pycharm": {
     "is_executing": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "年化收益率: -4.67 %\n"
     ]
    }
   ],
   "source": [
    "print('年化收益率:', compute_annual_profit(len(df), net_values[-1]), \"%\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 计算最大回撤\n",
    "\n",
    "~~~\n",
    "描述策略可能出现的最糟糕的情况，最极端可能的亏损情况。\n",
    "\n",
    "~~~\n",
    "\n",
    "\n",
    "- 计算公式\n",
    "    \n",
    "    $ Max Drawdown=Max(\\frac{Px−Py}{Px}) $\n",
    "    \n",
    "    $ Px,Py=策略某日净值，y>x $ "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "pycharm": {
     "is_executing": false
    }
   },
   "outputs": [],
   "source": [
    "def compute_drawdown(net_values):\n",
    "    \"\"\"\n",
    "    计算最大回撤\n",
    "    :param net_values: 净值列表\n",
    "    \"\"\"\n",
    "    # 最大回撤初始值设为0\n",
    "    max_drawdown = 0\n",
    "    index = 0\n",
    "    # 双层循环找出最大回撤\n",
    "    for net_value in net_values:\n",
    "        # 计算从当前开始直到结束，和当前净值相比的最大回撤\n",
    "        for sub_net_value in net_values[index:]:\n",
    "            # 计算回撤\n",
    "            drawdown = 1 - sub_net_value / net_value\n",
    "            # 如果当前的回撤大于已经计算的最大回撤，则当前回撤作为最大回撤\n",
    "            if drawdown > max_drawdown:\n",
    "                max_drawdown = drawdown\n",
    "        index += 1\n",
    "    return max_drawdown\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "pycharm": {
     "is_executing": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "最大回撤: 46.7 %\n"
     ]
    }
   ],
   "source": [
    "max_drawdown = compute_drawdown(list(net_values))\n",
    "print('最大回撤:', round(max_drawdown * 100, 2), \"%\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "最大回撤: 46.7 %\n"
     ]
    }
   ],
   "source": [
    "def compute_drawdown_oneloop(net_values):\n",
    "    \"\"\"\n",
    "    计算最大回撤\n",
    "    :param net_values: 净值列表\n",
    "    \"\"\"\n",
    "    # 最大回撤初始值设为0\n",
    "    max_drawdown = 0\n",
    "    i = 0\n",
    "    # 单层循环找出最大回撤\n",
    "    while i < len(net_values):\n",
    "        while i+1 < len(net_values) and net_values[i]<net_values[i+1]:\n",
    "            i += 1\n",
    "        j = i + 1\n",
    "        while j < len(net_values) and net_values[j]<net_values[i]:\n",
    "            if(1-net_values[j]/net_values[i]>max_drawdown):\n",
    "                max_drawdown = 1-net_values[j]/net_values[i]\n",
    "            j += 1\n",
    "        i = j  \n",
    "    return max_drawdown\n",
    "max_drawdown = compute_drawdown_oneloop(list(net_values))\n",
    "print('最大回撤:', round(max_drawdown * 100, 2), \"%\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 计算夏普比率\n",
    "\n",
    "~~~\n",
    "表示每承受一单位总风险，会产生多少的超额报酬，可以同时对策略的收益与风险进行综合考虑。\n",
    "~~~\n",
    "\n",
    "- 计算公式\n",
    "    \n",
    "    $ Sharpe Ratio = \\frac{R_p - R_f}{\\sigma_p  } $ \n",
    "    \n",
    "    $ R_p = 策略年化收益率  $\n",
    "    \n",
    "    $ R_f = 无风险利率  $\n",
    "    \n",
    "    $ \\sigma_p = 策略年化收益波动率 = 策略日化收益波动率 \\times \\sqrt{245}   $\n",
    "    \n",
    "  \n",
    "    \n",
    "    \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "pycharm": {
     "is_executing": false
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "def compute_sharpe_ratio(net_values):\n",
    "    \"\"\"\n",
    "    计算夏普比率\n",
    "    :param net_values: 净值列表\n",
    "    \"\"\"\n",
    "\n",
    "    # 总交易日数\n",
    "    trading_days = len(net_values)\n",
    "    # 所有收益的DataFrame\n",
    "    profit_df = pd.DataFrame(columns={'profit'})\n",
    "    # 收益之后，初始化为第一天的收益\n",
    "    profit_df.loc[0] = {'profit': round((net_values[0] - 1) * 100, 2)}\n",
    "    # 计算每天的收益\n",
    "    for index in range(1, trading_days):\n",
    "        # 计算每日的收益变化\n",
    "        profit = (net_values[index] - net_values[index - 1]) / net_values[index - 1]\n",
    "        profit = round(profit * 100, 2)\n",
    "        profit_df.loc[index] = {'profit': profit}\n",
    "\n",
    "    \n",
    "\n",
    "    # 计算当日收益标准差\n",
    "    profit_std = pow(profit_df['profit'].var(), 1 / 2)\n",
    "\n",
    "    # 年化收益\n",
    "    annual_profit = compute_annual_profit(trading_days, net_values[-1])\n",
    "\n",
    "    # 夏普比率\n",
    "    sharpe_ratio = (annual_profit - 4.75) / (profit_std * pow(245, 1 / 2))\n",
    "\n",
    "    return sharpe_ratio\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "pycharm": {
     "is_executing": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "夏普比率: -0.375\n"
     ]
    }
   ],
   "source": [
    "sharp = compute_sharpe_ratio(list(net_values))\n",
    "print('夏普比率:', round(sharp,3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 给定一个投资组合的收益序列，以沪深300作为参照，分解该投资组合的alpha和beta"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 获取数据, 计算收益序列\n",
    "\n",
    "~~~ \n",
    "以ZZ500ETF的收盘价，作为投资组合的净值序列\n",
    "\n",
    "~~~"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>510500.XSHG</th>\n",
       "      <th>000300.XSHG</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2018-12-28</th>\n",
       "      <td>4.451</td>\n",
       "      <td>3010.65</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-12-27</th>\n",
       "      <td>4.445</td>\n",
       "      <td>2990.51</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-12-26</th>\n",
       "      <td>4.501</td>\n",
       "      <td>3002.03</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-12-25</th>\n",
       "      <td>4.517</td>\n",
       "      <td>3017.28</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-12-24</th>\n",
       "      <td>4.577</td>\n",
       "      <td>3038.20</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            510500.XSHG  000300.XSHG\n",
       "2018-12-28        4.451      3010.65\n",
       "2018-12-27        4.445      2990.51\n",
       "2018-12-26        4.501      3002.03\n",
       "2018-12-25        4.517      3017.28\n",
       "2018-12-24        4.577      3038.20"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import tushare as ts\n",
    "\n",
    "\n",
    "target=\"510500.XSHG\" # 中证500ETF\n",
    "benchmark=\"000300.XSHG\" # 沪深300指数\n",
    "start=\"2015-1-1\"\n",
    "end=\"2018-12-31\"\n",
    "\n",
    "p_target = get_price(target, start_date=start, end_date=end, frequency='daily', fields=['close'], skip_paused=False, fq='pre')\n",
    "p_benchmark = get_price(benchmark, start_date=start, end_date=end, frequency='daily', fields=['close'], skip_paused=False, fq='pre')\n",
    "\n",
    "\n",
    "# 为避免投资组合的净值(价格)采样时间与基准的采样时间不同, 取两者的交集\n",
    "price= pd.concat([p_target, p_benchmark], axis=1, join='inner') \n",
    "price.columns=[target,benchmark]\n",
    "\n",
    "# 投资组合净值的时间顺序, 与参照基准的时间顺序, 这两者可能不同, 因此统一到时间降序上\n",
    "price.sort_index(ascending=False, inplace=True)\n",
    "price.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>510500.XSHG</th>\n",
       "      <th>000300.XSHG</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2018-12-28</th>\n",
       "      <td>0.001350</td>\n",
       "      <td>0.006735</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-12-27</th>\n",
       "      <td>-0.012442</td>\n",
       "      <td>-0.003837</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-12-26</th>\n",
       "      <td>-0.003542</td>\n",
       "      <td>-0.005054</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-12-25</th>\n",
       "      <td>-0.013109</td>\n",
       "      <td>-0.006886</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-12-24</th>\n",
       "      <td>0.008594</td>\n",
       "      <td>0.002905</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            510500.XSHG  000300.XSHG\n",
       "2018-12-28     0.001350     0.006735\n",
       "2018-12-27    -0.012442    -0.003837\n",
       "2018-12-26    -0.003542    -0.005054\n",
       "2018-12-25    -0.013109    -0.006886\n",
       "2018-12-24     0.008594     0.002905"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 计算收益\n",
    "r= (price-price.shift(-1))/price.shift(-1)\n",
    "r.drop(r.index[-1], inplace=True) \n",
    "r.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 计算$ \\beta $\n",
    "\n",
    "~~~\n",
    "表示投资的系统性风险。\n",
    "~~~\n",
    "\n",
    "- 计算公式\n",
    "    \n",
    "    $ \\beta = \\frac{Cov(r_P, r_B)} {Var(r_B)} $\n",
    "        \n",
    "    $ r_P = 投资组合P的超额收益率 = 投资组合每日收益率 - 日化无风险利率 $\n",
    "    \n",
    "    $ r_B = 业绩基准B的超额收益率 = 基准每日收益率 - 日化无风险利率  $\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.1407630051106075"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "riskfree = 0.02/245  # 日化无风险收益\n",
    "r_p = r[target]- riskfree\n",
    "r_b = r[benchmark]- riskfree\n",
    "beta=np.cov(r_p, r_b)[0,1]/np.var(r_b)\n",
    "beta\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 计算 $\\alpha $ \n",
    "\n",
    "~~~\n",
    "  投资中面临着系统性风险（即Beta）和非系统性风险（即Alpha），Alpha是投资者获得与市场波动无关的回报。\n",
    "~~~\n",
    "\n",
    "- 计算公式\n",
    "\n",
    "    $ Alpha = \\alpha = R_p - [R_f + \\beta_p \\times (R_b - R_f)])$\n",
    "    \n",
    "    $ R_p = 投资组合P的年化收益率 $\n",
    "    \n",
    "    $ R_b = 业绩基准B的年化收益率 $\n",
    "    \n",
    "    $ R_f = 无风险利率(年化) $\n",
    "    \n",
    "    $ \\beta_p = 投资组合P的\\beta值 $"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.051363236763159625"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Rf = 0.02   # 无风险利率(年化)\n",
    "profit =  (price[target][-1] - price[target][0])/price[target][0]\n",
    "\n",
    "# compute_annual_profit返回年化收益率的单位是%, 这里需要先转换成普通数值\n",
    "Rp = compute_annual_profit(len(price[target]), profit)/100\n",
    "\n",
    "profit =  (price[benchmark][-1] - price[benchmark][0])/price[benchmark][0]\n",
    "Rb = compute_annual_profit(len(r[benchmark]), profit)/100\n",
    "alpha= Rp - (Rf + beta*(Rb - Rf))\n",
    "alpha"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 习题一：根据HS300周净值序列， 分别计算年化收益、最大回撤、夏普比率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "pycharm": {
     "is_executing": false
    }
   },
   "outputs": [
    {
     "ename": "ModuleNotFoundError",
     "evalue": "No module named 'jqdatasdk'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-13-d413f2122ed5>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;31m# 样例： 从聚宽JQData获取HS300的周K数据\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;32mfrom\u001b[0m \u001b[0mjqdatasdk\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      4\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mpandas\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mpd\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'jqdatasdk'"
     ]
    }
   ],
   "source": [
    "# 样例： 从聚宽JQData获取HS300的周K数据\n",
    "\n",
    "from jqdatasdk import *\n",
    "import pandas as pd\n",
    "\n",
    "# ID是申请时所填写的手机号；Password为聚宽官网登录密码\n",
    "auth('ID','Password') \n",
    "\n",
    "pd.set_option('display.max_rows', 10)\n",
    "\n",
    "# 获取HS300周K收盘价\n",
    "df = get_price('000300.XSHG', start_date='2015-01-01', end_date='2018-12-31', frequency='5d', fields=['close'], skip_paused=False, fq='pre')\n",
    "first_close = df['close'][0]\n",
    "net_values = df['close']/ first_close\n",
    "net_values"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 习题二：使用ZZ500的周净值序列做为投资组合的收益序列，以HS300作为参照，分解alpha和beta。\n",
    "\n",
    "(建议，也可选用其他指数的日（或周）净值序列作为投资组合的收益序列，例如：上证50ETF，HS300ETF等)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {
    "pycharm": {
     "is_executing": false
    }
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  },
  "pycharm": {
   "stem_cell": {
    "cell_type": "raw",
    "metadata": {
     "collapsed": false
    },
    "source": []
   }
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": false,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "MarkDown菜单",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
